package mqclient

import (
	"context"
	"encoding/json"

	"gitee.com/gao-deguang/easy-chat/apps/task/mq/mq"
	"gitee.com/gao-deguang/easy-chat/pkg/wuid"
	"github.com/zeromicro/go-queue/kq"
	"github.com/zeromicro/go-zero/core/logx"
)

type MsgChatTransfer interface {
	Push(ctx context.Context, msg *mq.MsgChatTransfer) error
}

type MsgReadTransfer interface {
	Push(ctx context.Context, msg *mq.MsgMarkRead) error
}
type IBeforePush interface {
	BeforePush(ctx context.Context, msg *mq.MsgChatTransfer) error
}

type MsgChatTransferClient struct {
	pusher *kq.Pusher
}
type MsgReadTransferClient struct {
	pusher *kq.Pusher
}

func NewMsgChatTransferClient(addrs []string, topic string, opts ...kq.PushOption) *MsgChatTransferClient {
	return &MsgChatTransferClient{
		pusher: kq.NewPusher(addrs, topic),
	}
}

func NewMsgReadTransferClient(addrs []string, topic string, opts ...kq.PushOption) *MsgReadTransferClient {
	return &MsgReadTransferClient{
		pusher: kq.NewPusher(addrs, topic),
	}
}

func (c *MsgChatTransferClient) BeforePush(ctx context.Context, msg *mq.MsgChatTransfer) error {
	if msg.ConversationId == "" {
		msg.ConversationId = wuid.CombineId(msg.SendId, msg.RecvId)
	}
	return nil
}

func (c *MsgChatTransferClient) Push(ctx context.Context, msg *mq.MsgChatTransfer) error {
	c.BeforePush(ctx, msg)
	logx.Info("消息队列客户端AfterBeforePush的msg：", msg)
	body, err := json.Marshal(msg)
	if err != nil {
		return err
	}

	return c.pusher.Push(ctx, string(body))
}

func (c *MsgReadTransferClient) Push(ctx context.Context, msg *mq.MsgMarkRead) error {
	body, err := json.Marshal(msg)
	if err != nil {
		return err
	}

	return c.pusher.Push(ctx, string(body))
}
